package org.durandj.ystream.client.util;

import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;

/**
 * A utility class for working with the <code>ByteBuffer</code> class.
 * 
 * @author durandj
 * @version 1.0
 *
 */
public class ByteBufferUtils
{
	/**
	 * Converts a string into a byte buffer. A note on the specifics of how this done:
	 * to denote the end of the string a null is appended to
	 * the end of the string.
	 * 
	 * @param str - a string
	 * @return the equivalent byte buffer
	 */
	public static ByteBuffer stringToByteBuffer(String str)
	{
		if(str == null)
			throw new NullPointerException("Must give a valid string.");
		
		ByteBuffer buf = ByteBuffer.allocate((str.length() + 1) * 2);
		
		for(Character c : str.toCharArray())
			buf.putChar(c);
		
		buf.putChar('\0');
		
		return buf;
	}
	
	/**
	 * Adds a string to an existing byte buffer. This method will stop adding characters to the
	 * byte buffer if the byte buffer fills up before reaching the end of the string so
	 * if the full string is needed plan accordingly. A note on the specifics of how this is done:
	 * to denote the end of the string a null is appended to the end of the string.
	 * 
	 * @param buf - the byte buffer to add the string to
	 * @param str - the string
	 * @return the byte buffer with the string (this is for chaining)
	 */
	public static ByteBuffer addString(ByteBuffer buf, String str)
	{
		if(buf == null)
			throw new NullPointerException("Must give a valid byte buffer.");
		
		if(str == null)
			throw new NullPointerException("Must give a valid string.");
		
		try
		{
			for(Character c : str.toCharArray())
				buf.putChar(c);
			
			buf.putChar('\0');
		}
		catch(BufferOverflowException e)
		{ /* The byte buffer is full! */ }
		
		return buf;
	}
	
	/**
	 * Reads a string from a byte buffer until a null character is found or the end of the buffer
	 * is reached.
	 * 
	 * @param buf
	 * @return
	 */
	public static String getStringFromByteBuffer(ByteBuffer buf)
	{
		if(buf == null)
			throw new NullPointerException("Must give a valid byte buffer.");
		
		// Rewind the buffer to the beginning.
		buf.rewind();
		
		String str = "";
		Character c;
		while(buf.hasRemaining() && (c = buf.getChar()) != '\0')
			str += c;
		
		return str;
	}
}
